package com.yellow.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.yellow.dao.OrderSettingDao;
import com.yellow.pojo.OrderSetting;
import com.yellow.pojo.OrderSettingVo;
import com.yellow.service.OrderSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

@Service(interfaceClass = OrderSettingService.class)
@Transactional
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
    private OrderSettingDao orderSettingDao;

    @Override
    public void upload(List<OrderSetting> orderSettingList) {
        //判断当前上传的文件月份预约是否存在,存在就更新，不存在就添加
        ArrayList<OrderSetting> updatelist = new ArrayList<>();
        ArrayList<OrderSetting> addlist = new ArrayList<>();
        for (OrderSetting orderSetting : orderSettingList) {
            Date orderDate = orderSetting.getOrderDate();
            int count = orderSettingDao.findCountByDate(orderDate);
            if (count > 0) {
                //更新
                //优化方案：先保存到一个list中，然后一条sql执行 to do
//                orderSettingDao.updateOrderSetting(orderSetting);
                updatelist.add(orderSetting);
            } else {
                //添加
                //优化方案：先保存到一个list中，然后一条sql执行 to do
//                orderSettingDao.addOrderSetting(orderSetting);
                addlist.add(orderSetting);
            }
        }
        if (updatelist.size() >= 0) {
            orderSettingDao.updateOrderSettingByList(updatelist);
        }
        if (addlist.size() > 0) {
            orderSettingDao.addOrderSettingByList(addlist);
        }

    }

    @Override
    public List<OrderSettingVo> getOrderSettingByMonth(String date) {
        List<OrderSetting> orderSettingList = orderSettingDao.getOrderSettingByMonth(date);
        SimpleDateFormat sdf = new SimpleDateFormat("dd");
        List<OrderSettingVo> list = new ArrayList<>();
        for (OrderSetting orderSetting : orderSettingList) {
            OrderSettingVo vo = new OrderSettingVo();
            Date orderDate = orderSetting.getOrderDate();
            String format = sdf.format(orderDate);
            vo.setDate(Integer.parseInt(format));
            vo.setNumber(orderSetting.getNumber());
            vo.setReservations(orderSetting.getReservations());
            list.add(vo);
        }
//        System.out.println("list = " + list);
        return list;
    }

    @Override
    public void addOrderNumber(String date, int number) {
        Map<String, Object> map = new HashMap<>();
        map.put("date", date);
        map.put("number", number);
        orderSettingDao.addOrderNumber(map);
    }
}
